package gonat

import (
	"errors"
	"time"

	natpmp "github.com/jackpal/go-nat-pmp"
)

func DiscoverDevicePmp() (*PmpNatDevice, error) {
	// run external address lookups on all potential gateways
	found := make(chan *PmpNatDevice, len(potentialGateways))
	for i := range potentialGateways {
		gw := potentialGateways[i]
		go func() {
			c := natpmp.NewClient(gw)
			if _, err := c.GetExternalAddress(); err != nil {
				found <- nil
			} else {
				found <- &PmpNatDevice{"", nil, gw, c}
			}
		}()
	}
	// return the one that responds first.
	// discovery needs to be quick, so we stop caring about
	// any responses after a very short timeout.
	timeout := time.NewTimer(1 * time.Second)
	defer timeout.Stop()
	for range potentialGateways {
		select {
		case c := <-found:
			if c != nil {
				return c, nil
			}
		case <-timeout.C:
			return nil, errors.New("time out")
		}
	}
	return nil, errors.New("not found")
}
